//package com.daxt.common.config.cas;
//
//import com.daxt.common.result.ResultCode;
//import org.jasig.cas.client.authentication.*;
//import org.jasig.cas.client.util.AbstractCasFilter;
//import org.jasig.cas.client.util.CommonUtils;
//import org.jasig.cas.client.util.ReflectUtils;
//import org.jasig.cas.client.validation.Assertion;
//
//import javax.servlet.FilterConfig;
//import javax.servlet.*;
//import javax.servlet.http.Cookie;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import javax.servlet.http.HttpSession;
//import java.io.IOException;
//import java.util.HashMap;
//import java.util.Map;
//
//
//public class MyAuthenticationFilter extends AbstractCasFilter {
//    private String casServerLoginUrl;
//    private boolean renew = false;
//    private boolean gateway = false;
//    private GatewayResolver gatewayStorage = new DefaultGatewayResolverImpl();
//    private AuthenticationRedirectStrategy authenticationRedirectStrategy = new DefaultAuthenticationRedirectStrategy();
//    private UrlPatternMatcherStrategy ignoreUrlPatternMatcherStrategyClass = null;
//    private static final Map<String, Class<? extends UrlPatternMatcherStrategy>> PATTERN_MATCHER_TYPES = new HashMap<>();
//
//
//    @Override
//    protected void initInternal(FilterConfig filterConfig) throws ServletException {
//        if (!this.isIgnoreInitConfiguration()) {
//            super.initInternal(filterConfig);
//            this.setCasServerLoginUrl(this.getPropertyFromInitParams(filterConfig, "casServerLoginUrl", (String) null));
//            this.logger.trace("Loaded CasServerLoginUrl parameter: {}", this.casServerLoginUrl);
//            this.setRenew(this.parseBoolean(this.getPropertyFromInitParams(filterConfig, "renew", "false")));
//            this.logger.trace("Loaded renew parameter: {}", this.renew);
//            this.setGateway(this.parseBoolean(this.getPropertyFromInitParams(filterConfig, "gateway", "false")));
//            this.logger.trace("Loaded gateway parameter: {}", this.gateway);
//            String ignorePattern = this.getPropertyFromInitParams(filterConfig, "ignorePattern", (String) null);
//            this.logger.trace("Loaded ignorePattern parameter: {}", ignorePattern);
//            String ignoreUrlPatternType = this.getPropertyFromInitParams(filterConfig, "ignoreUrlPatternType", "REGEX");
//            this.logger.trace("Loaded ignoreUrlPatternType parameter: {}", ignoreUrlPatternType);
//            if (ignorePattern != null) {
//                Class ignoreUrlMatcherClass = PATTERN_MATCHER_TYPES.get(ignoreUrlPatternType);
//                if (ignoreUrlMatcherClass != null) {
//                    this.ignoreUrlPatternMatcherStrategyClass = ReflectUtils.newInstance(ignoreUrlMatcherClass.getName(), new Object[0]);
//                } else {
//                    try {
//                        this.logger.trace("Assuming {} is a qualified class name...", ignoreUrlPatternType);
//                        this.ignoreUrlPatternMatcherStrategyClass = ReflectUtils.newInstance(ignoreUrlPatternType, new Object[0]);
//                    } catch (IllegalArgumentException var6) {
//                        this.logger.error("Could not instantiate class [{}]", ignoreUrlPatternType, var6);
//                    }
//                }
//
//                if (this.ignoreUrlPatternMatcherStrategyClass != null) {
//                    this.ignoreUrlPatternMatcherStrategyClass.setPattern(ignorePattern);
//                }
//            }
//
//            String gatewayStorageClass = this.getPropertyFromInitParams(filterConfig, "gatewayStorageClass", (String) null);
//            if (gatewayStorageClass != null) {
//                this.gatewayStorage = ReflectUtils.newInstance(gatewayStorageClass, new Object[0]);
//            }
//
//            String authenticationRedirectStrategyClass = this.getPropertyFromInitParams(filterConfig, "authenticationRedirectStrategyClass", (String) null);
//            if (authenticationRedirectStrategyClass != null) {
//                this.authenticationRedirectStrategy = ReflectUtils.newInstance(authenticationRedirectStrategyClass, new Object[0]);
//            }
//        }
//
//    }
//
//    @Override
//    public void init() {
//        super.init();
//        CommonUtils.assertNotNull(this.casServerLoginUrl, "casServerLoginUrl cannot be null.");
//    }
//
//    @Override
//    public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        HttpServletResponse response = (HttpServletResponse) servletResponse;
//
////        response.setHeader("Access-Control-Allow-Origin","*");
////        response.setHeader("Content-Type","application/x-www-form-urlencoded");
//
//
//
//        // 判断请求是否不需要过滤
//        if (this.isRequestUrlExcluded(request)) {
//            this.logger.debug("Request is ignored.");
//            filterChain.doFilter(request, response);
//            return;
//        }
//        System.out.println("==============:"+request.getRequestURI());
//
//        HttpSession session = request.getSession(false);
//        Assertion assertion = session != null ? (Assertion) session.getAttribute("_const_cas_assertion_") : null;
//        // 存在assertion,即认为这是一个已通过认证的请求.予以放行
//        if (assertion != null) {
//            filterChain.doFilter(request, response);
//            return;
//        }
//
//        // 不存在 assertion,那么就来判断这个请求是否是用来校验ST的(校验通过后会将信息写入assertion)
//        final String serviceUrl = constructServiceUrl(request, response);
//        final String ticket = retrieveTicketFromRequest(request);
//        final boolean wasGatewayed = this.gateway && this.gatewayStorage.hasGatewayedAlready(request, serviceUrl);
//        // 是校验ST的请求,予以放行
//        if (CommonUtils.isNotBlank(ticket) || wasGatewayed) {
////            System.out.println("2222222:"+request.getRequestURI());
////            response.sendRedirect("http://192.168.137.1/api"+request.getRequestURI()+"?jsessionid=" + request.getSession().getId());
//            filterChain.doFilter(request, response);
//            return;
//        }
//
//        String modifiedServiceUrl;
//
//        logger.debug("no ticket and no assertion found");
//        if (this.gateway) {
//            logger.debug("setting gateway attribute in session");
//            modifiedServiceUrl = this.gatewayStorage.storeGatewayInformation(request, serviceUrl);
//        } else {
//            modifiedServiceUrl = serviceUrl;
//        }
//
//        logger.debug("Constructed service url: {}", modifiedServiceUrl);
//
////        // 要重定向界面地址(cas服务端登录界面).
////        String urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl,
////                getProtocol().getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway);
//
////        modifiedServiceUrl = "http://192.168.0.200:7502/checkTicket";
////        String urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl, this.getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway);
////        String skipUrl = "{\"code\":\"" + ResultCode.SKIP.getCode() + "\", \"msg\":\"no ticket and no assertion found\", \"url\":\"" + urlToRedirectTo + "\"}";
////        response.getWriter().write(skipUrl);
////
////
////        logger.debug("redirecting to \"{}\"", urlToRedirectTo);
////        this.authenticationRedirectStrategy.redirect(request, response, urlToRedirectTo);
//
//
//////        modifiedServiceUrl = "http://192.168.0.200:7502/checkTicket";
////        modifiedServiceUrl = "http://10.10.20.77/prod-api/checkTicket";
//        modifiedServiceUrl = "http://192.168.137.1/api/index/checkTicket";
////        modifiedServiceUrl = "http://192.168.137.1:7502/checkTicket";
//        String urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl, this.getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway);
//        String xRequested = request.getHeader("x-requested-with");
//        this.logger.debug("redirecting to \"{}\"", urlToRedirectTo);
//        if ("XMLHttpRequest".equals(xRequested)) {
//            String skipUrl = "{\"code\":\"" + ResultCode.SKIP.getCode() + "\", \"msg\":\"no ticket and no assertion found\", \"url\":\"" + urlToRedirectTo + "\"}";
//            response.getWriter().write(skipUrl);
//        } else {
//            this.authenticationRedirectStrategy.redirect(request, response, urlToRedirectTo);
//        }
//
//
//    }
//
//    public final void setRenew(boolean renew) {
//        this.renew = renew;
//    }
//
//    public final void setGateway(boolean gateway) {
//        this.gateway = gateway;
//    }
//
//    public final void setCasServerLoginUrl(String casServerLoginUrl) {
//        this.casServerLoginUrl = casServerLoginUrl;
//    }
//
//    public final void setGatewayStorage(GatewayResolver gatewayStorage) {
//        this.gatewayStorage = gatewayStorage;
//    }
//
//    private boolean isRequestUrlExcluded(HttpServletRequest request) {
//        if (this.ignoreUrlPatternMatcherStrategyClass == null) {
//            return false;
//        } else {
//            StringBuffer urlBuffer = request.getRequestURL();
//            if (request.getQueryString() != null) {
//                urlBuffer.append("?").append(request.getQueryString());
//            }
//
//            String requestUri = urlBuffer.toString();
//            return this.ignoreUrlPatternMatcherStrategyClass.matches(requestUri);
//        }
//    }
//
//    static {
//        PATTERN_MATCHER_TYPES.put("CONTAINS", ContainsPatternUrlPatternMatcherStrategy.class);
//        PATTERN_MATCHER_TYPES.put("REGEX", RegexUrlPatternMatcherStrategy.class);
//        PATTERN_MATCHER_TYPES.put("EXACT", ExactUrlPatternMatcherStrategy.class);
//    }
//}
